using Microsoft.EntityFrameworkCore;

namespace ZZ_ICU.Models
{
    // 应用程序的数据库上下文：集中管理实体集合及其映射关系。
    public class ApplicationDbContext : DbContext
    {
        // 通过依赖注入获取 DbContextOptions（包含连接字符串、提供程序等）。
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        // DbSet 映射表/视图
        public DbSet<NurseInfo> NurseInfo { get; set; } = null!;
        public DbSet<BedInfo> BedInfo { get; set; } = null!;
        public DbSet<PatientViewInfo> PatientViewInfo { get; set; } = null!;
        public DbSet<PatientInfo> PatientInfo { get; set; } = null!;

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // 配置表名
            modelBuilder.Entity<NurseInfo>().ToTable("NurseInfo");
            modelBuilder.Entity<BedInfo>().ToTable("BedInfo");
            // 视图映射（不跟踪主键以避免 SQL Server 对视图键约束要求）
            modelBuilder.Entity<PatientViewInfo>().HasNoKey().ToView("ZZJH_V_PatientInfo");

            // 配置主键
            modelBuilder.Entity<NurseInfo>().HasKey(n => n.Id);
            modelBuilder.Entity<BedInfo>().HasKey(b => b.Id);

            // 配置字段属性（长度/必填等约束应与数据库结构保持一致）
            modelBuilder.Entity<NurseInfo>().Property(n => n.Name).HasMaxLength(50).IsRequired();
            modelBuilder.Entity<NurseInfo>().Property(n => n.UserNo).HasMaxLength(50).IsRequired();
            modelBuilder.Entity<NurseInfo>().Property(n => n.Password).HasMaxLength(50).IsRequired();
            modelBuilder.Entity<NurseInfo>().Property(n => n.JobTitle).HasMaxLength(50).IsRequired();
            modelBuilder.Entity<NurseInfo>().Property(n => n.Dept).HasMaxLength(50).IsRequired();
            modelBuilder.Entity<NurseInfo>().Property(n => n.IsDel).IsRequired();
            modelBuilder.Entity<BedInfo>().Property(b => b.BedNo).HasMaxLength(50).IsRequired();
            modelBuilder.Entity<BedInfo>().Property(b => b.Nurse).HasMaxLength(50).IsRequired(false);
            // 列名为 Type，但实体中属性名为 UserType，避免与保留名冲突
            modelBuilder.Entity<NurseInfo>().Property(n => n.UserType).HasColumnName("Type").IsRequired(false);
            modelBuilder.Entity<NurseInfo>().Property(n => n.UserEnableTime).IsRequired(false);
            modelBuilder.Entity<NurseInfo>().Property(n => n.UserDisableTime).IsRequired(false);
            modelBuilder.Entity<PatientInfo>().ToTable("PatientInfo");
            modelBuilder.Entity<PatientInfo>().HasKey(p => p.Id);
        }
    }
}
